﻿using CustomItem;
using InventorySystem.Items;
using InventorySystem.Items.Pickups;
using InventorySystem.Items.ThrowableProjectiles;
using System.Collections.Generic;
using CustomItem.Interfaces;
using UnityEngine;

[ItemInfo("冲击手榴弹", ItemType.GrenadeHE, WeightMultiplier = 0.5f)]
public class ImpactGrenade : CustomItem.CustomItem, IRoundStartSpawn
{
    public ImpactGrenade(ushort serial, bool active = true, ItemBase ib = null, ItemPickupBase ipb = null) : base(serial, active, ib, ipb)
    {
    }

    private ExplosionGrenade Grenade = null;

    public SpawnRule Rule => new SpawnRule()
    {
        StackSpawn = false,
        MaxStacks = 0,
        Offset = 3,
        SpawnableStructures = new Structure[] { Structure.MiscLocker },
        SpawnableRooms = new MapGeneration.RoomName[] { },
        SpawnChance = 1f,
        SpawnCount = 5
    };

    public override void Item_Onactive()
    {
        base.Item_Onactive();
        Exiled.Events.Handlers.Player.ThrownProjectile += Player_ThrownProjectile;
    }

    private void Player_ThrownProjectile(Exiled.Events.EventArgs.Player.ThrownProjectileEventArgs ev)
    {
        if (ev.Projectile.Base.NetworkInfo.Serial == Serial)
        {
            Grenade = ev.Projectile.Base as ExplosionGrenade;
            List<Keyframe> keyframes = new List<Keyframe>();
            foreach (var a in Grenade._playerDamageOverDistance.keys)
            {
                var key = a;
                key.value *= 0.3f;
                keyframes.Add(key);
            }
            Grenade._playerDamageOverDistance.keys = keyframes.ToArray();
            Rigidbody rb = (Grenade.PhysicsModule as PickupStandardPhysics).Rb;
            ev.Projectile.Scale = Vector3.one * 0.2f;
            rb.AddForce(ev.Player.CameraTransform.forward * 10f, ForceMode.VelocityChange);
            Grenade.OnCollided += PickupGrenade_OnCollided;
        }
    }

    private void PickupGrenade_OnCollided(Collision obj)
    {
        if (obj.collider.gameObject.layer != 0)
        {
            return;
        }
        Grenade.OnCollided -= PickupGrenade_OnCollided;
        Grenade.Network_syncTargetTime = 0.1f;
    }

    public override void Item_Ondeactive()
    {
        base.Item_Ondeactive();
        Exiled.Events.Handlers.Player.ThrownProjectile -= Player_ThrownProjectile;
    }
}